package com.erp.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Map<String, Object>> handleValidationExceptions(MethodArgumentNotValidException ex) {
        Map<String, Object> errorDetails = new HashMap<>();
        errorDetails.put("code", 400);
        errorDetails.put("msg", "数据校验失败");

        Map<String, String> fieldErrors = new HashMap<>();
        ex.getBindingResult().getFieldErrors().forEach(error -> 
            fieldErrors.put(error.getField(), error.getDefaultMessage())
        );
        errorDetails.put("errors", fieldErrors);

        // 增强错误信息的可读性
        StringBuilder errorMessage = new StringBuilder();
        for (Map.Entry<String, String> entry : fieldErrors.entrySet()) {
            errorMessage.append(entry.getKey()).append(": ").append(entry.getValue()).append("; ");
        }
        errorDetails.put("details", errorMessage.toString());

        return new ResponseEntity<>(errorDetails, HttpStatus.OK);
    }
}